import { createSignal, For, Show,onMount,onCleanup } from 'solid-js'
import MessageItem from './MessageItem'
import IconSend from './icons/send'
import type { ChatMessage } from '../types'
let timer = null; 

export default () => {
  let inputRef: HTMLInputElement
  const [messageList, setMessageList] = createSignal<ChatMessage[]>([])
  const [defaultList,setDefaultList] = createSignal<ChatMessage[]>([])
  const [currentAssistantMessage, setCurrentAssistantMessage] = createSignal('')
  const [loading, setLoading] = createSignal(false)
  const [isError, setIsError] = createSignal(false)

  setDefaultList([
    ...defaultList(),
    {
      role: 'system',
      content: `龙宝智能AI为您服务：

1、 知乎百度答题、作业题目

2、写文案、写论文，写小说、写脚本

3、文案润色、翻译、写诗作词

4、扮演面试官、扮演书籍电影角色

5、倾诉、解忧、讲故事......

---------------

例1：写一篇工作日报我是行政

例2：把下文翻译成英文：xxx

例3：写一出能活的短视频剧本

---------------
或者可以问我其他问题
           
越完整的描述，我越精确哟!`,
    }
  ])
  // setMessageList([
  //   {
  //     role: 'user',
  //     content: '越完整的描述，我越精确哟',
  //   }, {
  //     role: 'assistant',
  //     content: '12312323',
  //   }, {
  //     role: 'assistant',
  //     content: '或者可以问我其他问题或者可以问我其他问题或者可以问我其他问题或者可以问我其他问题或者可以问我其他问题或者可以问我其他问题或者可以问我其他问题',
  //   },
  // ])
  onCleanup(() => clearInterval(timer));
  onMount(() =>{
    // 获取页面高度
    let windowHeight = window.innerHeight;
    // 监听页面高度变化
    window.addEventListener('resize', () => {
      const newHeight = window.innerHeight;
      if (newHeight !== windowHeight) {
        // 更新页面高度
        document.body.style.height = `${newHeight}px`;
        windowHeight = newHeight;
      }
    });
  })

  function  getMobileSystem() {
    var u = navigator.userAgent
    var isAndroid = u.indexOf('Android') > -1 || u.indexOf('Adr') > -1 //android系统
    var isiOS = !!u.match(/\(i[^;]+;( U;)? CPU.+Mac OS X/) //ios系统
    var iphoneX = /iphone/gi.test(navigator.userAgent) && screen.height == 812 && screen.width == 375
    // 返回1是android系统
    if (isAndroid) {
      return 1
    }
    // 返回2是ios系统
    if (isiOS && !iphoneX) {
      return 2
    }
    // 返回3是iphoneX
    if (iphoneX) {
      return 3
    }
    return 0
  }
  // 滚动到页面底部
  const scrollToBottom = () => {
    window.scrollTo({
      top: document.documentElement.offsetHeight,
      left: 0,
      behavior: "smooth",
    });
  };


  // input获取焦点时
  const inputFocus = () =>{
    // if(getMobileSystem() == 1){
    //   const input = document.querySelector('input');
    //   const inputRect = input.getBoundingClientRect();
    //   const inputTop = inputRect.top + window.scrollY;
    //   window.scrollTo(0, inputTop);
    // }else{
    //   scrollToBottom()
    // }
    scrollToBottom()
  }

  const handleButtonClick = async () => {
    const inputValue = inputRef.value
    if (!inputValue) {
      return
    }
    setLoading(true)
    // @ts-ignore
    inputRef.value = ''
    setMessageList([
      ...messageList(),
      {
        role: 'user',
        content: inputValue,
      },
    ])
    scrollToBottom()
    const response = await fetch('/api/generate', {
      method: 'POST',
      body: JSON.stringify({
        messages: messageList(),
      }),
    })
    timer = setInterval(() =>{
      scrollToBottom()  
    },500)
    if (!response.ok) {
      setIsError(true)
      clearInterval(timer)
      throw new Error(response.statusText)
    }
    const data = response.body
    if (!data) {
      setIsError(true)
      clearInterval(timer)
      throw new Error('No data')
    }
    const reader = data.getReader()
    const decoder = new TextDecoder('utf-8')
    let done = false

    while (!done) {
      const { value, done: readerDone } = await reader.read()
      if (value) {
        let char = decoder.decode(value)
        if (char === '\n' && currentAssistantMessage().endsWith('\n')) {
          continue
        }
        if (char) {
          setCurrentAssistantMessage(currentAssistantMessage() + char)
        }
      }
      done = readerDone
    }
    setMessageList([
      ...messageList(),
      {
        role: 'assistant',
        content: currentAssistantMessage(),
      },
    ])

    scrollToBottom()  
    setCurrentAssistantMessage('')
    setLoading(false)
    clearInterval(timer)
  }

  const clear = () => {
    inputRef.value = ''
    setMessageList([])
    setCurrentAssistantMessage('')
  }

  return (
    <div my-6>
      <For each={defaultList()}>{(defaultList) => <MessageItem role={defaultList.role} message={defaultList.content} />}</For>
      <For each={messageList()}>{(message) => <MessageItem role={message.role} message={message.content} />}</For>
      { currentAssistantMessage() && <MessageItem role="assistant" message={currentAssistantMessage} /> }
      <Show when={!loading()} fallback={() => <div class="flex items-center gap-2 footer"><div class="footer-center">AI正在思考中...</div></div>}>
        <div class="flex items-center gap-2 footer">
          <input
            ref={inputRef!}
            type="text"
            id="input"
            placeholder="请输入..."
            autocomplete='off'
            autofocus
            disabled={loading()}
            onfocus={inputFocus}
            onKeyDown={(e) => {
              e.key === 'Enter' && !e.isComposing && handleButtonClick()
            }}
            w-full
            px-4
            h-12
            text-slate
            rounded-sm
            bg-slate
            bg-op-15
            focus:bg-op-20
            focus:ring-0
            focus:outline-none
            placeholder:text-slate-400
            placeholder:op-30
            class="send-input"
          />
          <button onClick={handleButtonClick} disabled={loading()} h-12 px-2 py-2 bg-slate bg-op-15 hover:bg-op-20 text-slate rounded-sm class="send">
           <IconSend />
          </button>
        </div>
      </Show>
      <Show when={isError()}>
        <div class="transition-opacity is-alert is-error">AI繁忙，请刷新页面后重试!</div>
      </Show>
    </div>
  )
}
